package com.youyun56.gps.android;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.SharedPreferences.Editor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.HandlerThread;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;

import com.youyun56.gps.android.broadcast.CloseSystemDialogBroadCast;
import com.youyun56.gps.android.common.ApplicationUtils;
import com.youyun56.gps.android.common.BaseActovity;
import com.youyun56.gps.android.common.CommandFactory;
import com.youyun56.gps.android.common.JSONKey;
import com.youyun56.gps.android.common.NetWorkUtil;
import com.youyun56.gps.android.common.PathConfig;
import com.youyun56.gps.android.common.PreferenceKeys;
import com.youyun56.gps.android.http.HttpManager;
import com.youyun56.gps.android.http.IHttpListener;
import com.youyun56.gps.android.pojo.Car;
import com.youyun56.gps.android.pojo.Im;
import com.youyun56.gps.android.pool.MessageHander;
import com.youyun56.gps.android.service.LocationUploadService;

public class GpsActivity extends BaseActovity {
    private EditText            txtUserName;
    private EditText            txtPwd;
    private CheckBox            chkRemember;
    private Button              btnLogin;
    final static String         tag           = GpsActivity.class.getName();
    private ProgressDialog      pd;
    public static String        imsi;
    private HandlerThread       handlerThread = new HandlerThread(tag);
    public static MessageHander handler;
    private ProgressDialog      pBar;
    public final static String  userName      = "userName";
    public final static String  pwd           = "pwd";
    private File                downFile      = new File(Environment.getExternalStorageDirectory(), "youyun.apk");
    
    protected void onPause() {
        super.onPause();
        Log.i(tag, "pause");
    }
    
    @Override
    protected void onStop() {
        // TODO Auto-generated method stub
        super.onStop();
        Log.i(tag, "stop");
    }
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        System.gc();
        if (!NetWorkUtil.isGprsOpen(this)) {
            NetWorkUtil.openGprs(this, true);
        }
        imsi = ApplicationUtils.getIMSI(this);
        startService();
        PathConfig.setROOT(getApplicationContext().getFilesDir().getAbsolutePath());
        preference = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
        handlerThread.start();
        handler = new MessageHander(this, this.getMainLooper());
        setContentView(R.layout.main);
        txtUserName = (EditText) findViewById(R.id.txtUserName);
        txtUserName.setText(preference.getString(userName, ""));
        txtPwd = (EditText) findViewById(R.id.txtPwd);
        txtPwd.setText(preference.getString(pwd, ""));
        chkRemember = (CheckBox) findViewById(R.id.chkRemember);
        chkRemember.setChecked(preference.getBoolean(PreferenceKeys.REMEMBER_USER, true));
        btnLogin = (Button) findViewById(R.id.btnLogin);
        final String version = ApplicationUtils.getVersion(this);
        btnLogin.setOnClickListener(new View.OnClickListener() {
            
            @Override
            public void onClick(View v) {
                CloseSystemDialogBroadCast.setOpen(true);
                pd = new ProgressDialog(GpsActivity.this);
                pd.setTitle("登录");
                pd.setMessage("登录中,请稍候...");
                pd.setProgressStyle(ProgressDialog.STYLE_SPINNER);
                pd.show();
                GpsActivity.this.runOnUiThread(new Runnable() {
                    
                    @Override
                    public void run() {
                        Editor editor = preference.edit();
                        if (chkRemember.isChecked()) {
                            editor.putString(userName, txtUserName.getText().toString()).commit();
                            editor.putString(pwd, txtPwd.getText().toString()).commit();
                        } else {
                            editor.putString(userName, "").commit();
                            editor.putString(pwd, "").commit();
                        }
                        String carId = txtUserName.getText().toString();
                        String pwd = txtPwd.getText().toString();
                        HttpManager.getInstance().excutePost(CommandFactory.login(carId, pwd, version, imsi), new IHttpListener() {
                            
                            @Override
                            public void onBack(boolean bSuccess, String strData, int nResponseCode) {
                                // TODO Auto-generated method stub
                                if (bSuccess) {
                                    try {
                                        final JSONObject input = new JSONObject(strData);
                                        Boolean success = input.getBoolean("success");
                                        if (success) {
                                            LocationUploadService service = GpsActivity.this.getService();
                                            Car car = new Car();
                                            if (!input.isNull("CAR")) {
                                                JSONObject carO = input.getJSONObject("CAR");
                                                car.setId(carO.getLong("id"));
                                                car.setCarId(carO.getString("carId"));
                                                car.setPartner(carO.getInt("partner"));
                                                car.setCarMobile(carO.getString("carMobile"));
                                                car.setPwd(carO.getString("pwd"));
                                                car.setProvince(carO.getInt("province"));
                                                car.setCityId(carO.getInt("cityId"));
                                                car.setLastPositionTime(carO.getString("lastPositionTime"));
                                                car.setCarryStatus(carO.getString("carryStatus"));
                                                car.setPosition(carO.getString("position"));
                                                car.setFocusCity(car.getCityId());
                                                car.setProvince(13);
                                                car.setCityId(124);
                                                service.setCar(car);
                                                service.getPreference().edit().putLong("id", car.getId()).commit();
                                            }
                                            if (service.getCar().getPartner() == LocationUploadService.gpsUpload) {
                                                
                                                if (!service.startGps(input.getLong("gpsinterval"))) {
                                                    GpsActivity.this.getPd().dismiss();
                                                    new AlertDialog.Builder(GpsActivity.this).setTitle("提示").setMessage("手机不支持定位，请打开GPS设备")// 设置内容
                                                        .setPositiveButton("确定",// 设置确定按钮
                                                            new DialogInterface.OnClickListener() {
                                                                
                                                                @Override
                                                                public void onClick(DialogInterface dialog, int which) {
                                                                    GpsActivity.this.startActivity(new Intent("android.settings.LOCATION_SOURCE_SETTINGS"));
                                                                    
                                                                }
                                                                
                                                            }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                                            public void onClick(DialogInterface dialog, int whichButton) {
                                                                // 点击"取消"按钮之后退出程序
                                                                dialog.dismiss();
                                                            }
                                                        }).create().show();
                                                }
                                            } else {
                                                GpsFactory.factory.stop();
                                            }
                                            Intent intent = new Intent();
                                            intent.setClass(GpsActivity.this, MainTabActivity.class);
                                            GpsActivity.this.startActivity(intent);
                                            if (!input.isNull(JSONKey.IMS)) {
                                                List<Im> ims = service.getIms();
                                                JSONArray array = input.getJSONArray(JSONKey.IMS);
                                                for (int i = 0; i < array.length(); i++) {
                                                    JSONObject o = array.getJSONObject(i);
                                                    Im im = new Im();
                                                    im.setAddDay(o.getString("addDay"));
                                                    im.setAttach(o.getString("attach"));
                                                    im.setContext(o.getString("context"));
                                                    im.setUserId(o.getLong("userId"));
                                                    ims.add(im);
                                                }
                                            }
                                            service.setRunStep(RunStep.MAIN);
                                            GpsActivity.this.getPd().dismiss();
                                            GpsActivity.this.finish();
                                        } else {
                                            String error = input.getString("msgs");
                                            if (input.has("version")) {
                                                GpsActivity.this.getPd().dismiss();
                                                new AlertDialog.Builder(GpsActivity.this).setTitle("系统更新").setMessage(error)// 设置内容
                                                    .setPositiveButton("确定",// 设置确定按钮
                                                        new DialogInterface.OnClickListener() {
                                                            
                                                            @Override
                                                            public void onClick(DialogInterface dialog, int which) {
                                                                pBar = new ProgressDialog(GpsActivity.this);
                                                                pBar.setTitle("正在下载");
                                                                pBar.setMessage("请稍候...");
                                                                pBar.setProgressStyle(ProgressDialog.STYLE_SPINNER);
                                                                try {
                                                                    downFile(String.format("http://1683333.com/downfiles/youyun56%s.apk", input.getString("version")));
                                                                } catch (JSONException e) {
                                                                    Log.e(tag, e.getMessage(), e);
                                                                }
                                                                
                                                            }
                                                            
                                                        }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                                        public void onClick(DialogInterface dialog, int whichButton) {
                                                            // 点击"取消"按钮之后退出程序
                                                            dialog.dismiss();
                                                        }
                                                    }).create().show();
                                            } else if (input.has("imis")) {
                                                GpsActivity.this.getPd().dismiss();
                                                new AlertDialog.Builder(GpsActivity.this).setTitle("错误序列号").setMessage(error).setNeutralButton("确定",// 设置确定按钮
                                                    new DialogInterface.OnClickListener() {
                                                        
                                                        @Override
                                                        public void onClick(DialogInterface dialog, int which) {
                                                            dialog.dismiss();
                                                        }
                                                        
                                                    }).create().show();
                                            } else {
                                                GpsActivity.this.getPd().dismiss();
                                                new AlertDialog.Builder(GpsActivity.this).setTitle("错误").setMessage(new StringBuffer(error)).setNeutralButton("确定",// 设置确定按钮
                                                    new DialogInterface.OnClickListener() {
                                                        
                                                        @Override
                                                        public void onClick(DialogInterface dialog, int which) {
                                                            dialog.dismiss();
                                                        }
                                                        
                                                    }).create().show();
                                            }
                                        }
                                    } catch (JSONException e) {
                                        // TODO Auto-generated catch block
                                        Log.e(tag, e.getMessage(), e);
                                    } catch (Exception e) {
                                        // TODO Auto-generated catch block
                                        Log.e(tag, e.getMessage(), e);
                                    }
                                } else {
                                    pd.dismiss();
                                    new AlertDialog.Builder(GpsActivity.this).setTitle("失败").setMessage("连接失败,请稍候再试...").setNeutralButton("确定", new OnClickListener() {
                                        
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            dialog.dismiss();
                                        }
                                    }).create().show();
                                }
                            }
                            
                            void downFile(final String url) {
                                pBar.show();
                                new Thread() {
                                    public void run() {
                                        HttpClient client = new DefaultHttpClient();
                                        // params[0]代表连接的url
                                        HttpGet get = new HttpGet(url);
                                        HttpResponse response;
                                        try {
                                            response = client.execute(get);
                                            HttpEntity entity = response.getEntity();
                                            long length = entity.getContentLength();
                                            InputStream is = entity.getContent();
                                            FileOutputStream fileOutputStream = null;
                                            if (is != null) {
                                                
                                                fileOutputStream = new FileOutputStream(downFile);
                                                
                                                byte[] buf = new byte[1024];
                                                int ch = -1;
                                                int count = 0;
                                                while ((ch = is.read(buf)) != -1) {
                                                    // baos.write(buf, 0, ch);
                                                    fileOutputStream.write(buf, 0, ch);
                                                    count += ch;
                                                    if (length > 0) {
                                                        
                                                    }
                                                    
                                                }
                                                
                                            }
                                            fileOutputStream.flush();
                                            if (fileOutputStream != null) {
                                                fileOutputStream.close();
                                            }
                                            down();
                                        } catch (Exception e) {
                                            Log.e(tag, e.getMessage(), e);
                                        }
                                    }
                                    
                                }.start();
                                
                            }
                            
                            void down() {
                                pBar.cancel();
                                Intent intent = new Intent(Intent.ACTION_VIEW);
                                intent.setDataAndType(Uri.fromFile(downFile), "application/vnd.android.package-archive");
                                GpsActivity.this.startActivity(intent);
                            }
                            
                        });
                    }
                });
            }
        });
    }
    
    @Override
    protected RunStep getRunStep() {
        // TODO Auto-generated method stub
        return RunStep.LOGIN;
    }
    
    @Override
    protected void onDestroy() {
        this.unbindService(mServiceConnection);
        super.onDestroy();
        Log.i(tag, "destroy");
    }
    
    public Button getBtnLogin() {
        return btnLogin;
    }
    
    public LocationUploadService getService() {
        return service;
    }
    
    public ProgressDialog getPd() {
        return pd;
    }
    
}
